﻿using System.Collections.Generic;
using EPiBoost.Core.Plugins.Gui.Admin.ContentTypeManager.Model;
using EPiBoost.Plugins.ContentTypeManager.Model;
using EPiServer.DataAbstraction;
using EPiServer.ServiceLocation;

namespace EPiBoost.Core.Plugins.Gui.Admin.ContentTypeManager
{
    public static class ContentTypeLoader
    {
	    public static List<ContentTypeInfo> LoadPageTypes()
			{
				var result = new List<ContentTypeInfo>();

				var repository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
				var modelRepo = ServiceLocator.Current.GetInstance<ContentTypeModelRepository>();
				
				var types = repository.List();
				foreach (var contentType in types)
				{
					// load content type
					var r = new ContentTypeInfo()
						{
							ContentTypeName = contentType.Name,
							ContentTypeDisplayName = contentType.DisplayName,
							ContentTypeGuid = contentType.GUID,
							IsPageType = contentType is PageType,
							IsBlockType = contentType is BlockType
						};

					// load content properties
					foreach (var propertyDefinition in contentType.PropertyDefinitions)
					{
						var p = new ContentPropertyInfo()
							{
								PropertyDefinitionId = propertyDefinition.ID,
								EditCaption = propertyDefinition.EditCaption,
								PropertyName = propertyDefinition.Name,
								TypeName = propertyDefinition.Type.Name,
								ExistsOnModel = !IsMissingModelProperty(propertyDefinition, modelRepo),
							};
							r.ContentProperties.Add(p);
					}

					// add to list
					result.Add(r);
				}

				return result;
			}

			private static bool IsMissingModelProperty(PropertyDefinition propertyDefinition, ContentTypeModelRepository repository)
			{
				return (((propertyDefinition != null) 
								&& propertyDefinition.ExistsOnModel) 
								&& (repository.GetPropertyModel(propertyDefinition.ContentTypeID, propertyDefinition) == null));
			}

			public static void RemoveProperties(List<ContentTypeInfo> selectedProperties)
			{
				var contentRepo = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
				var propertyRepo = ServiceLocator.Current.GetInstance<IPropertyDefinitionRepository>();

				foreach (var contentType in selectedProperties)
				{
					var ct = contentRepo.Load(contentType.ContentTypeGuid);
					if (ct != null)
					{
						foreach (var deletedProperty in contentType.ContentProperties)
						{
							var p = propertyRepo.Load(deletedProperty.PropertyDefinitionId);
							if (p != null)
							{
								propertyRepo.Delete(p);	
							}
						}
					}
				}
			}
		}
}
